import React from 'react';
import { DragSource } from 'react-dnd';
import { getEmptyImage } from 'react-dnd-html5-backend';

/**
 * 从然哥18年写的 react-dnd copy过来的
 *
 * 页面左侧图标可拖拽组件块
 */
class DataDragItem extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    //链接拖拽的预览图片，用官方api给定一个空图片
    this.props.connectDragPreview(getEmptyImage(), {
      captureDraggingState: true,
    });
  }

  // 渲染名称，主要处理搜索时的数据高亮
  renderResourceName=(resourceName)=>{
    let { keyWord, hoverItem, widget } = this.props
    if (keyWord && resourceName.toLowerCase().indexOf(keyWord.toLowerCase()) !== -1) {
      if (hoverItem.reportColumnId === widget.id || hoverItem.id === widget.id) {
        return (
          <span style={{ color: '#4B8DFF' }}>{resourceName}</span>
        )
      } else {
        return(
          <span dangerouslySetInnerHTML={{__html: resourceName.replace(new RegExp(`${keyWord.toLowerCase()}`, 'img'), function(arg1){
              return `<span style='color: #4B8DFF'>${arg1}</span>`})
          }} />
        )
      }

    } else {
      if (hoverItem.reportColumnId === widget.id || hoverItem.id === widget.id) {
        return (
          <span style={{ color: '#4B8DFF' }}>{resourceName}</span>
        )
      } else {
        return resourceName
      }

    }
  }

  render() {
    const { widget, id } = this.props;
    const { connectDragSource, hoverItem } = this.props;
    let highLight = (hoverItem.reportColumnId === widget.id) || (hoverItem.id === widget.id);
    return connectDragSource(
      <div className={'data-drag-item-wrapper'} onClick={(e) => {
        e.stopPropagation();
        e.preventDefault();
        this.props.onItemClick(widget);
      }} draggable={true} id={id}>
        <div className={`touch-area ${highLight ? 'high-light' : ''}`}>
          {this.renderResourceName(widget.columnDisplayName) || '-'}
        </div>
      </div>
    );
  }
}

DataDragItem.propTypes = {
  widget: React.PropTypes.object,
  connectDragSource: React.PropTypes.func.isRequired,  //自动注入
  connectDragPreview: React.PropTypes.func.isRequired,  //自动注入
  isDragging: React.PropTypes.bool.isRequired
};

export default DragSource(
  'data-item',
  {
    beginDrag(props) {
      return props.widget;
    },
    endDrag(props) {
      props.onDragEnd && props.onDragEnd();
      return props.widget;
    }
  },
  (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    connectDragPreview: connect.dragPreview(),
    isDragging: monitor.isDragging(),
  }))(DataDragItem);
